package org.sunyaxing.transflow.api.extensions.base.typesimpl;

import cn.hutool.core.map.MapUtil;
import org.sunyaxing.transflow.api.HandleData;
import org.sunyaxing.transflow.api.TransData;
import org.sunyaxing.transflow.api.extensions.base.ExtensionContext;
import org.sunyaxing.transflow.api.extensions.base.types.TransFlowMiddleHandler;

import java.util.Optional;

/**
 * 每个 处理器都会取数据的transData处理一次
 *
 * @param <T>
 */
public abstract class TransFlowMiddleEachHandler<T, FT, FR, R> extends TransFlowMiddleHandler<T, FT, FR, R> {
    public TransFlowMiddleEachHandler(ExtensionContext extensionContext) {
        super(extensionContext);
    }

    @Override
    public Optional<HandleData<R>> exec(HandleData<T> handleData) {
        TransData<FT> transRes = beforeHandle(handleData);
        if (MapUtil.isNotEmpty(this.handlerMap)) {
            this.handlerMap.forEach((k, function) -> {
                function.apply(transRes);
            });
        }
        HandleData<R> result = afterHandle(transRes);
        return Optional.of(result);
    }

    public abstract TransData<FT> beforeHandle(HandleData<T> handleData);

    public abstract HandleData<R> afterHandle(TransData<FT> transRes);
}
